package com.thiswhyme.demo.msgpush.core.impl.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: session管理器
 * @author: thiswhyme
 * @date: 2021/9/27
 */
@Slf4j
public class SessionManager {

    private SessionManager() {}

    /**
     * 用户连接session池
     */
    private static ConcurrentHashMap<String, WebSocketSession> userSessionMap = new ConcurrentHashMap<>();

    /**
     * 获取所有session连接
     * @return
     */
    public static Map<String, WebSocketSession> getAll() {
        return userSessionMap;
    }

    /**
     * 获取session
     * @param key
     * @return
     */
    public static WebSocketSession get(String key) {
        return userSessionMap.get(key);
    }

    /**
     * 添加 session
     * @param key
     */
    public static void add(String key, WebSocketSession session) {
        userSessionMap.put(key, session);
        log.info("添加{}的session，当前共{}条", key, userSessionMap.size());
    }

    /**
     * 移除指定用户指定ID的session
     * @param key
     */
    public static void removeBySessionId(String key, String sessionId) {
        WebSocketSession session = userSessionMap.get(key);
        if (session == null || !sessionId.equals(session.getId())) {
            return;
        }
        userSessionMap.remove(key);
        log.info("移除{}的session，当前共{}条", key, userSessionMap.size());
    }

    /**
     * 移除指定用户除指定ID以外的session
     * @param key
     */
    public static void removeOtherSession(String key, String sessionId) {
        WebSocketSession session = userSessionMap.get(key);
        if (session == null || sessionId.equals(session.getId())) {
            return;
        }
        userSessionMap.remove(key);
        log.info("移除{}的session，当前共{}条", key, userSessionMap.size());
    }
}
